﻿/*******************************************************************************
Copyright (c) 2011-2013, PKStudio
Copyright (c) 2011,      Zynga Inc.
Copyright (c) 2008-2010, Ricardo Quesada
Copyright (c) 2009,      Valentin Milea

http://pkstudio.org

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*******************************************************************************/

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace PKEngine
{
	/// <summary>
	/// PKActionManager is a singleton that manages all the actions.
	/// Normally you won't need to use this singleton directly.
	/// 99% of the cases you will use the PKNode interface, which uses this singleton.
	/// But there are some cases where you might need to use this singleton.
	/// Examples:
	/// 	- When you want to run an action where the target is different from a PKNode. 
	/// 	- When you want to pause / resume the actions.
	/// </summary>
	public class PKActionManager : IPKUpdate
	{
		#region ActionListItem
		/// <summary>
		/// Items of action list.
		/// </summary>
		private class TargetListItem
		{
			public PKNode Target { get; set; }
			public List<PKAction> ActionList { get; set; }
			public int ActionIndex { get; set; }
			public bool IsPaused { get; set; }

			public TargetListItem(PKNode target, bool isPaused)
			{
				this.Target = target;
				this.ActionList = new List<PKAction>();
				this.ActionIndex = -1;
				this.IsPaused = isPaused;
			}
		}
		#endregion

		#region Singleton
		private static PKActionManager _sharedManager;

		public static PKActionManager SharedManager
		{
			get
			{
				if (_sharedManager == null)
				{
					_sharedManager = new PKActionManager();
					PKScheduler.SharedScheduler.ScheduleUpdateForTarget(_sharedManager, 0, false);
				}
				return _sharedManager;
			}
		}
		#endregion

		#region Private Fields
		private List<TargetListItem> targetList;
		private int targetIndex;
		#endregion

		#region Initialization
		public PKActionManager()
		{
			this.targetList = new List<PKActionManager.TargetListItem>();
			this.targetIndex = -1;
		}
		#endregion

		#region Public Methods
		/// <summary>
		/// Adds an action with a target.
		/// If the target is already present, then the action will be added to the existing target.
		/// If the target is not present, a new instance of this target will be created either paused or not, and the action will be added to the newly created target.
		/// When the target is paused, the queued actions won't be 'ticked'.
		/// </summary>
		/// <param name="action">The action need to be added</param>
		/// <param name="target">The target PKNode</param>
		/// <param name="paused">If the action is paused</param>
		public void AddAction(PKAction action, PKNode target, bool paused)
		{
			Debug.Assert(target != null, "PKActionManager.AddAction: Argument cannot be null.");
			Debug.Assert(action != null, "PKActionManager.AddAction: Argument cannot be null.");

			TargetListItem item = PKActionManager.FindTargetListItemHelper(targetList, target);
			if (item == null)
			{
				item = new PKActionManager.TargetListItem(target, paused);
				targetList.Add(item);
			}

			Debug.Assert(!item.ActionList.Contains(action), "PKActionManager.AddAction: Action has been added.");
			item.ActionList.Add(action);

			action.StartWithTarget(target);
		}

		/// <summary>
		/// Removes all actions from all the targets.
		/// </summary>
		public void ClearActions()
		{
			foreach (TargetListItem item in targetList)
			{
				item.ActionList.Clear();
			}
			targetList.Clear();
		}

		/// <summary>
		/// Removes all actions from a certain target.
		/// </summary>
		/// <param name="target">The target PKNode</param>
		public void RemoveAllActionsFromTarget(PKNode target)
		{
			if (target == null)
			{
				return;
			}

			int index = PKActionManager.FindIndexOfTargetListItemHelper(targetList, target);
			if (index != -1)
			{
				if (targetIndex != -1 && index <= targetIndex)
				{
					targetIndex--;
				}
				targetList[index].ActionList.Clear();
				targetList.RemoveAt(index);
			}
		}

		/// <summary>
		/// Removes an action given an action reference.
		/// </summary>
		/// <param name="action">The action which will be removed</param>
		public void RemoveAction(PKAction action)
		{
			if (action == null)
			{
				return;
			}

			TargetListItem item = PKActionManager.FindTargetListItemHelper(targetList, action.OriginalTarget);
			if (item != null)
			{
				int index = item.ActionList.IndexOf(action);
				if (index != -1)
				{
					if (item.ActionIndex != -1 && index <= item.ActionIndex)
					{
						item.ActionIndex--;
					}
					item.ActionList.RemoveAt(index);
					if (item.ActionList.Count == 0)
					{
						this.RemoveAllActionsFromTarget(item.Target);
					}
				}
			}
		}

		/// <summary>
		/// Removes an action given its tag and the target.
		/// </summary>
		/// <param name="tag">Specified tag</param>
		/// <param name="target">The target PKNode</param>
		public void RemoveActionByTag(int tag, PKNode target)
		{
			Debug.Assert(target != null, "PKActionManager.RemoveActionByTag: Argument cannot be null.");
			Debug.Assert(tag != PKAction.PKActionInvalidTag, "IPKActionManager.RemoveActionByTag: Invalid action tag.");

			TargetListItem item = PKActionManager.FindTargetListItemHelper(targetList, target);
			if (item != null)
			{
				int index = PKActionManager.FindIndexOfActionHelper(item.ActionList, tag);
				if (index != -1)
				{
					Debug.Assert(item.ActionList[index].OriginalTarget == target, "PKActionManager.RemoveActionByTag: Action is not running action of specified target.");
					if (item.ActionIndex != -1 && index <= item.ActionIndex)
					{
						item.ActionIndex--;
					}
					item.ActionList.RemoveAt(index);
					if (item.ActionList.Count == 0)
					{
						this.RemoveAllActionsFromTarget(item.Target);
					}
				}
			}
		}

		/// <summary>
		/// Gets an action given its tag an a target.
		/// </summary>
		/// <param name="tag">Specified tag</param>
		/// <param name="target">The target PKNode</param>
		/// <returns>The action with specified tag</returns>
		public PKAction GetActionByTag(int tag, PKNode target)
		{
			Debug.Assert(target != null, "PKActionManager.GetActionByTag: Argument cannot be null.");
			Debug.Assert(tag != PKAction.PKActionInvalidTag, "PKActionManager.GetActionByTag: Invalid action tag.");

			TargetListItem item = PKActionManager.FindTargetListItemHelper(targetList, target);
			if (item != null)
			{
				PKAction action = PKActionManager.FindActionHelper(item.ActionList, tag);
				if (action != null)
				{
					Debug.Assert(action.OriginalTarget == target, "PKActionManager.GetActionByTag: Action is not running action of specified target.");
					return action;
				}
			}

			return null;
		}

		/// <summary>
		/// Returns the numbers of actions that are running in a certain target.
		/// Composable actions are counted as 1 action. Example:
		/// 	If you are running 1 Sequence of 7 actions, it will return 1.
		/// 	If you are running 7 Sequences of 2 actions, it will return 7.
		/// </summary>
		/// <param name="target">The target PKNode</param>
		/// <returns>Numbers of running actions</returns>
		public int NumberOfRunningActionsInTarget(PKNode target)
		{
			if (target == null)
			{
				return 0;
			}

			TargetListItem item = PKActionManager.FindTargetListItemHelper(targetList, target);
			if (item != null)
			{
				return item.ActionList.Count;
			}

			return 0;
		}

		/// <summary>
		/// Pauses the target: all running actions and newly added actions will be paused.
		/// </summary>
		/// <param name="target">Target PKNode</param>
		public void PauseTarget(PKNode target)
		{
			foreach (TargetListItem item in targetList)
			{
				if (item.Target == target)
				{
					item.IsPaused = true;
					break;
				}
			}
		}

		/// <summary>
		/// Resumes the target. All queued actions will be resumed.
		/// </summary>
		/// <param name="target">Target PKNode</param>
		public void ResumeTarget(PKNode target)
		{
			foreach (TargetListItem item in targetList)
			{
				if (item.Target == target)
				{
					item.IsPaused = false;
					break;
				}
			}
		}

		/// <summary>
		/// Pauses all running targets.
		/// </summary>
		/// <returns>Targets whose actions were paused</returns>
		public List<PKNode> PauseAllRunningTargets()
		{
			List<PKNode> pausedTargets = new List<PKNode>();
			foreach (TargetListItem item in targetList)
			{
				if (!item.IsPaused)
				{
					item.IsPaused = true;
					pausedTargets.Add(item.Target);
				}
			}
			return pausedTargets;
		}

		/// <summary>
		/// Resume a set of targets. (convenience function to reverse a PauseAllRunningActions call)
		/// </summary>
		/// <param name="targetsToResume">Targets to resume</param>
		public void ResumeTargets(List<PKNode> targetsToResume)
		{
			foreach (PKNode target in targetsToResume)
			{
				this.ResumeTarget(target);
			}
		}

		/// <summary>
		/// Update method.
		/// </summary>
		/// <param name="dt">Delta time</param>
		public void Update(float dt)
		{
			for (targetIndex = 0; targetIndex < targetList.Count; targetIndex++)
			{
				TargetListItem currentTarget = targetList[targetIndex];

				if (!currentTarget.IsPaused)
				{
					for (currentTarget.ActionIndex = 0; currentTarget.ActionIndex < currentTarget.ActionList.Count; currentTarget.ActionIndex++)
					{
						PKAction action = currentTarget.ActionList[currentTarget.ActionIndex];

						action.Step(dt);
						if (action.IsDone)
						{
							action.Stop();
							this.RemoveAction(action);
						}
					}
					currentTarget.ActionIndex = -1;
				}
			}
			targetIndex = -1;
		}
		#endregion

		#region Private Methods
		private static TargetListItem FindTargetListItemHelper(List<TargetListItem> list, PKNode target)
		{
			foreach (TargetListItem item in list)
			{
				if (item.Target == target)
				{
					return item;
				}
			}

			return null;
		}

		private static int FindIndexOfTargetListItemHelper(List<TargetListItem> list, PKNode target)
		{
			for (int i = 0; i < list.Count; i++)
			{
				TargetListItem item = list[i];
				if (item.Target == target)
				{
					return i;
				}
			}

			return -1;
		}

		private static PKAction FindActionHelper(List<PKAction> list, int tag)
		{
			foreach (PKAction item in list)
			{
				if (item.Tag == tag)
				{
					return item;
				}
			}

			return null;
		}

		private static int FindIndexOfActionHelper(List<PKAction> list, int tag)
		{
			for (int i = 0; i < list.Count; i++)
			{
				PKAction item = list[i];
				if (item.Tag == tag)
				{
					return i;
				}
			}

			return -1;
		}
		#endregion
	}
}
